import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:im_base/public/global/global.dart';
import 'package:im_base/public/tim/components/chat/emoji/view.dart';
import 'package:im_base/public/tim/components/chat/menus/view.dart';
import 'package:im_base/public/ext/string_ext.dart';
import 'package:permission_handler/permission_handler.dart';

import 'logic.dart';
import 'state.dart';

class InputWidget extends StatelessWidget {
  late final InputLogic logic;

  late final InputState state;

  InputWidget({String? id}) {
    logic = Get.put(InputLogic(), tag: id);
    state = logic.state;
    state.id = id;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
            color: Colors.grey[100],
            border:
                Border(top: BorderSide(color: Color(0xFFE0E0E0), width: 1))),
        child: Column(children: [inputBar(), holderWidget()]));
  }

  ///emoji 表情选择盘,更多菜单,软键盘占位widget
  ///如果是emoji,则展示emoji
  ///如果是更多菜单,则展示更多菜单widget
  ///如果是软键盘弹出,则展示占位widget
  ///否则不展示
  Widget holderWidget() {
    return GetBuilder<InputLogic>(
        id: EMOJI_WIDGET,
        init: logic,
        tag: state.id,
        builder: (logic) {
          return logic.state.isEmoji
              ? EmojiWidget(state.id??'')
              : logic.state.showMore
                  ? MenusWidget(state.id)
                  : logic.state.showKeyBoard
                      ? Container(
                          height: Global.KEYBOARD_HEIGHT,
                        )
                      : Container();
        });
  }

  ///输入框,语音操作栏
  Widget inputBar() {
    return Container(
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          audioEdit(),
          GetBuilder<InputLogic>(
              id: INPUT_AREA,
              init: logic,
              tag: state.id,
              builder: (logic) {
                return Expanded(
                    child:
                        logic.state.isAudio ? audioBox(logic) : editBox(logic));
              }),
          GetBuilder<InputLogic>(
              id: EMOJI_EDIT,
              init: logic,
              tag: state.id,
              builder: (logic) {
                return IconButton(
                    splashColor: Colors.transparent,
                    highlightColor: Colors.transparent,
                    onPressed: () {
                      logic.toggleEmoji();
                    },
                    icon: Image.asset(getEmojiIcon(logic.state.isEmoji)));
              }),
          sendMore()
        ],
      ),
    );
  }

  ///发送按钮 更多按钮
  Widget sendMore() {
    return GetBuilder<InputLogic>(
      init: logic,
      tag: state.id,
      builder: (logic) {
        return Container(
            width: 50,
            alignment: Alignment.center,
            child: logic.state.inputContent.isNullEmpty()
                ? IconButton(
                    splashColor: Colors.transparent,
                    highlightColor: Colors.transparent,
                    onPressed: () {
                      logic.showMore();
                    },
                    icon: Image.asset(
                        '${Global.IMAGE_PATH}ic_input_more_normal.png'),
                  )
                : ButtonTheme(
                    layoutBehavior: ButtonBarLayoutBehavior.constrained,
                    height: 30,
                    minWidth: 35,
                    child: TextButton(
                      onPressed: () {
                        logic.sendMessage();
                      },
                      child: Text(
                        '发送',
                        style: TextStyle(color: Colors.white, fontSize: 12),
                      ),
                      style: ButtonStyle(
                          minimumSize: MaterialStateProperty.all(Size(35, 30)),
                          backgroundColor:
                              MaterialStateProperty.all(Colors.green)),
                    ),
                  ));
      },
      id: SEND_MORE,
    );
  }

  ///语音文字输入切换按钮
  Widget audioEdit() {
    return GetBuilder<InputLogic>(
        init: logic,
        tag: state.id,
        id: AUDIO_EDIT_ID,
        builder: (logic) {
          return IconButton(
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent,
              onPressed: () {
                logic.toggleAudio();
              },
              icon: Image.asset(getInputIcon(logic.state.isAudio)));
        });
  }

  ///语音输入框
  Widget audioBox(InputLogic logic) {
    return Container(
        height: 40,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6),
          color: Colors.white,
        ),
        padding: EdgeInsets.only(left: 4, right: 4),
        margin: EdgeInsets.only(top: 8, bottom: 8),
        child: GestureDetector(
          onLongPressStart: (detail) async {
            if (await Permission.microphone.status.isGranted) {
              logic.audioPressStart(detail.localPosition.dy);
            } else {
              logic.requestPermission();
            }
          },
          onLongPressEnd: (detail) {
            logic.audioPressEnd();
          },
          onLongPressMoveUpdate: (detail) {
            logic.audioPressMove(detail.localPosition.dy);
          },
          child: TextButton(
            onPressed: null,
            child: Text(
              logic.state.audioHint,
              style: TextStyle(color: Colors.black87, fontSize: 14),
            ),
          ),
        ));
  }

  ///文字输入框
  Widget editBox(InputLogic logic) {
    return Container(
      constraints: BoxConstraints(minHeight: 40, maxHeight: 120),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(6),
        color: Colors.white,
      ),
      padding: EdgeInsets.only(left: 4, right: 4),
      margin: EdgeInsets.only(top: 8, bottom: 8),
      child: LayoutBuilder(builder: (context, size) {
        ///这里通过计算输入文字的长度决定是否需要回行
        TextSpan text = new TextSpan(
          text: logic.state.inputContent,
          style: TextStyle(color: Colors.black87, fontSize: 14),
        );

        TextPainter tp = new TextPainter(
          text: text,
          textDirection: TextDirection.ltr,
          textAlign: TextAlign.left,
        );
        tp.layout(maxWidth: size.maxWidth);

        int lines = (tp.size.height / tp.preferredLineHeight).ceil();
        int maxLines = 4;

        return TextField(
          key: Key(state.id??''),
          controller: logic.state.editingController,
          minLines: 1,
          maxLines: lines < maxLines ? null : maxLines,
          textInputAction: TextInputAction.send,
          onSubmitted: (value)=>logic.sendMessage(),
          decoration: InputDecoration(
              border: InputBorder.none,
              isDense: true,
              isCollapsed: true,
              contentPadding: EdgeInsets.symmetric(vertical: 12)),
          style: TextStyle(color: Colors.black87, fontSize: 14),
          onChanged: (v) {
            logic.updateInputContent(v);
          },
        );
      }),
    );
  }

  ///如果当前为键盘,则展示语音图标,如果为语音,则展示键盘图标
  String getInputIcon(bool isAudio) {
    return isAudio
        ? '${Global.IMAGE_PATH}ic_input_keyboard_normal.png'
        : '${Global.IMAGE_PATH}ic_input_voice_normal.png';
  }

  ///如果当前为键盘,则展示语音图标,如果为语音,则展示键盘图标
  String getEmojiIcon(bool isEmoji) {
    return isEmoji
        ? '${Global.IMAGE_PATH}ic_input_keyboard_normal.png'
        : '${Global.IMAGE_PATH}ic_input_face_normal.png';
  }
}
